#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct node
{
    node(int x,int y,int v)
        :i(x),j(y),val(v)
    {}
    int i;
    int j;
    int val;
};

class check
{
public:
    bool operator()(const node& n1, const node& n2)
    {
        return n1.val > n2.val;
    }
};

bool checkValidGrid(vector<vector<int>>& grid) {
    priority_queue<node, vector<node>, check> pq;
    int n = grid.size(), m = grid[0].size();

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            pq.push(node(i, j, grid[i][j]));
        }
    }

    pq.pop();
    int pi = 0, pj = 0;
    while (!pq.empty())
    {
        node top = pq.top();
        pq.pop();
        int i = top.i;
        int j = top.j;

        int deli = abs(i - pi);
        int delj = abs(j - pj);

        if (deli == 2 && delj == 1 || deli == 1 && delj == 2)
        {
            pi = i;
            pj = j;
        }
        else
            return false;
    }
    return true;
}


int main()
{
    vector<vector<int>> vv = { {0,11,16,5,20},{17,4,19,10,15},{12,1,8,21,6},{3,18,23,14,9},{24,13,2,7,22} };
    cout << checkValidGrid(vv);
    return 0;
}